package io.terminus.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import io.terminus.spzx.consts.UserInfoConstant;
import io.terminus.spzx.model.entity.user.UserInfo;
import io.terminus.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc 用户登录权限拦截器
 * @date 2024-11-18
 */
@Component
@RequiredArgsConstructor
public class UserLoginAuthInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 如果token不为空，那么此时验证token的合法性
        String cacheUserInfo = redisTemplate.opsForValue().get(UserInfoConstant.REDIS_USERINFO_TOKEN_KEY_PREFIX + request.getHeader(UserInfoConstant.USERINFO_TOKEN_REQUEST_HEADER));
        AuthContextUtil.setUserInfo(JSON.parseObject(cacheUserInfo, UserInfo.class));

        return true;
    }
}
